package com.noexcs.forum.controller;

import com.noexcs.forum.annotation.LoginRequired;
import com.noexcs.forum.entity.User;
import com.noexcs.forum.service.LikeService;
import com.noexcs.forum.service.UserService;
import com.noexcs.forum.util.ForumUtil;
import com.noexcs.forum.util.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author noexcs
 * @since 5/22/2022 12:18 PM
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Value("${forum.path.upload}")
    String uploadPath;

    @Value("${forum.path.domain}")
    String domain;

    @Value("${server.servlet.context-path}")
    String contextPath;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    UserService userService;

    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage() {
        return "site/setting";
    }

    @LoginRequired
    @PostMapping("/upload")
    public String updateHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "未选择文件！");
            return "site/setting";
        }

        String filename = headerImage.getOriginalFilename();
        filename = ForumUtil.generateUUID() + filename.substring(filename.lastIndexOf("."));

        String url = uploadPath + "/" + filename;
        File saveFile = new File(url);
        try {
            headerImage.transferTo(saveFile);
            String headerUrl = domain + contextPath + "/user/header/" + filename;
            userService.updateHeader(hostHolder.getUser().getId(), headerUrl);
        } catch (IOException e) {
            log.error("保存头像文件失败");
            model.addAttribute("error", "上传失败");
            return "site/setting";
        }
        return "redirect:/index";
    }

    @GetMapping("/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        fileName = uploadPath + "/" + fileName;
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        response.setContentType("img/" + suffix);
        try (FileInputStream fis = new FileInputStream(fileName);
             ServletOutputStream servletOutputStream = response.getOutputStream()) {
            byte[] bytes = new byte[1024];
            int b = 0;
            while ((b = fis.read(bytes)) != -1) {
                servletOutputStream.write(bytes, 0, b);
            }
        } catch (IOException e) {
            log.error("读取文件失败");
        }
    }

    @Autowired
    LikeService likeService;

    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("user", user);

        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        return "site/profile";
    }

}
